package com.example.testkafka.consumer.listener;

import org.apache.kafka.clients.consumer.ConsumerInterceptor;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.OffsetAndMetadata;
import org.apache.kafka.common.TopicPartition;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class TestConsumerInterceptor implements ConsumerInterceptor<String,String> {
    @Override
    public ConsumerRecords<String, String> onConsume(ConsumerRecords<String, String> consumerRecords) {

        Set<TopicPartition> topicPartitions = consumerRecords.partitions();
        for(TopicPartition topicPartition : topicPartitions){
            List<ConsumerRecord<String,String>> records = consumerRecords.records(topicPartition);
            for(int i = 0;i < records.size();i ++){
                if(records.get(i).value().contains("1")){
                    try {
                        Field field = ConsumerRecord.class.getDeclaredField("value");
                        field.setAccessible(true);
                        field.set(records.get(i),"*****" + records.get(i).value() + "*****");
                    } catch (NoSuchFieldException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return consumerRecords;
    }

    @Override
    public void onCommit(Map<TopicPartition, OffsetAndMetadata> map) {

        map.forEach((tp,offset) -> {
            System.out.println("分区:" + tp + " 提交的位移是:" + offset);
        });
    }

    @Override
    public void close() {

    }

    @Override
    public void configure(Map<String, ?> map) {

    }
}
